package com.soft.blog_project.controller;

import com.soft.blog_project.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Random;

@Api(tags = "用户模块")
@RestController
@CrossOrigin(origins="*")
public class UserController {
    @Autowired(required=false)//初始化对象(这一句可以解决17行jdbc红色)
    private JdbcTemplate jdbc;
    //登陆
    //http://localhost:8088/doLogin 使用post方式
    @ApiOperation(value = "用户登录",
            protocols = "http",
            httpMethod = "POST",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @PostMapping("/doLogin")
    public Result doLogin(@RequestBody User user) {//前端的数据进行封装

        //1.得到前端数据
        System.out.println(user);
        //初始化
        Result result=new Result();
        //2.得到数据库数据
        User userinfo=null;
        try{
            userinfo=jdbc.queryForObject("select * from user where account=? and password=?",
                    new BeanPropertyRowMapper<>(User.class),user.getAccount(),user.getPassword()
            );
            result.setCode(200);
            result.setResult(userinfo);
            return result;//返回对象
        }catch(DataAccessException e) {
            e.printStackTrace();//异常打印
            result.setCode(201);
            result.setResult("出现异常"+e.getMessage());
            return result;
        }
        //3.校验
        //如果有对象直接返回，没有对象返回空
    }


    //根据电话号码返回对应的验证码
    @ApiOperation(value = "返回验证码",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "根据电话号码返回对应的验证码,code:200表示成功，201表示异常")
    @GetMapping("/Exam")
    public Result Exam(@ApiParam(name = "phone", value = "电话号码", required = true)String phone){
        Result result=new Result();
        try {
            result.setCode(200);
            result.setResult(
                    jdbc.queryForObject("select exam from user where phone=?",Integer.class,phone)
            );
        } catch (DataAccessException e) {
            result.setCode(201);
            result.setResult("验证码异常"+e.getMessage());
        }
        return result;
    }

    //删除(根据账号）
    //http://localhost:8088/doDelete?Account=zhangsan
    @ApiOperation(value = "删除账号",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @GetMapping("/doDelete")
    public Result DeleteByName(String Account){
        Result result=new Result();
        //1.得到前端数据
        //System.out.println(user);

        //2.插入数据到数据库,在实际工作中要判断用户名是否存在
        try {
            jdbc.update("delete from user where account = ?",Account);
            //3.逻辑判断返回相应数据
            result.setCode(200);
            result.setResult("删除成功！");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("出现异常"+e.getMessage());
            return result;
        }
    }

    //搜索用户（根据用户名）
    //http://localhost:8088/BlogByAuthor?Author=张三
    @ApiOperation(value = "搜索用户（根据用户名）",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @GetMapping("/BlogByAuthor")
    public Result QueryBlogByAuthor(String Author){
        Result result=new Result();
        try {
            result.setCode(200);
            result.setResult(
                    jdbc.query("select * from user where user_name =?",
                            new BeanPropertyRowMapper<>(BlogAndUser.class),Author));
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("出现异常"+e.getMessage());
            return result;
        }
    }

    //注册
    @ApiOperation(value = "用户注册",
            protocols = "http",
            httpMethod = "POST",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示注册成功，201表示注册异常，2021表示注册失败，用户名重复，2011表示注册失败，姓名或用户名或密码为空")
    @PostMapping("/doRegister")
    public Result doRegister(@RequestBody User user){
        Result result = new Result();
        System.out.println(user);
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        if (user.getAccount()!=null && user.getPassword()!=null && user.getUserName()!=null &&
                user.getAccount() != "" && user.getPassword()!="" && user.getUserName()!="") {
            try {
                Integer accountexist = jdbc.queryForObject("select count(*) from user where account = ?", Integer.class, user.getAccount());
                if (accountexist*1 == 0) {
                    try {
                        jdbc.update("insert into user(user_name, account, password, phone, age, city, sex, sign,exam)\n" +
                                        "value (?,?,?,?,?,?,?,?,?);",user.getUserName(),user.getAccount(),user.getPassword(),user.getPhone(),
                                user.getAge(),user.getCity(),user.getSex(),user.getSign(),randomNumber);
                        result.setCode(200);
                        result.setResult("注册成功！");
                    } catch (DataAccessException e) {
                        e.printStackTrace();
                        result.setCode(201);
                        result.setResult("注册异常"+e.getMessage());
                    }
                } else {
                    result.setCode(2012);
                    result.setResult("注册失败！用户名重复");
                }
                return result;
            } catch (DataAccessException e) {
                e.printStackTrace();
                result.setCode(201);
                result.setResult("异常"+e.getMessage());
                return result;
            }
        } else {
            result.setCode(2011);
            result.setResult("注册失败！姓名或用户名或密码不能为空");
            return result;
        }
    }

    //修改密码
    //前端来比对输入的密码是否符合，这里只管新密码，并且要求前端同时返回id
    @ApiOperation(value = "修改密码",
            protocols = "http",
            httpMethod = "POST",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示修改成功，201表示修改失败")
    @PostMapping("/updataPassword")
    public Result updataPassword(@RequestBody User user){
        Result result = new Result();
        System.out.println(user);
        try {
            jdbc.update("update user set password = ? where User_id = ?;",user.getPassword(),user.getUserId());
            result.setCode(200);
            result.setResult("修改成功");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("修改失败"+e.getMessage());
            return result;
        }
    }

    //修改账户名，创新点可以是模仿微博，修改要交钱
    //要求前端同时返回id
    @ApiOperation(value = "修改账户名",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示修改成功，201表示修改失败，2012表示用户名重复")
    @GetMapping("/updataAccount")
    public Result updataAccount(@ApiParam(name = "account", value = "账户名称", required = true)String account,
                                @ApiParam(name = "userId", value = "用户ID", required = true)Integer userId){
        Result result = new Result();
        try {
            Integer accountexist = jdbc.queryForObject("select count(*) from user where account = ?", Integer.class, account);
            if(accountexist == 0){
                try {
                    jdbc.update("update user set account = ? where User_id = ?;",account,userId);
                    result.setCode(200);
                    result.setResult("修改成功");
                } catch (DataAccessException e) {
                    e.printStackTrace();
                    result.setCode(201);
                    result.setResult("修改失败"+e.getMessage());
                }
            }else{
                result.setCode(2012);
                result.setResult("修改失败！用户名重复");
            }
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("修改失败"+e.getMessage());
            return result;
        }

    }

    //修改个性签名
    @ApiOperation(value = "修改个性签名",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示修改成功，201表示修改异常")
    @GetMapping("/updataSign")
    public Result updataSign(@ApiParam(name = "sign", value = "个性签名", required = true)String sign,
                             @ApiParam(name = "userId", value = "用户ID", required = true)Integer userId){
        Result result = new Result();
        try {
            jdbc.update("update user set sign = ? where User_id = ?;",sign,userId);
            result.setCode(200);
            result.setResult("修改成功");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("修改失败"+e.getMessage());
            return result;
        }
    }

    @ApiOperation(value = "我的关注",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功显示我所关注用户的个人信息，201表示显示异常")
    @GetMapping("/userFollow")
    public Result userFollowById(@ApiParam(name = "userId", value = "用户ID", required = true)Integer userId){
        Result result = new Result();
        try {
            List<userFollow> followuserlist = jdbc.query("select user.User_id, user_name, account, city, sign, user_img, phone, age\n" +
                    "from user join (select follow_id from follow where user_id = ?) as f\n" +
                    "where user.User_id = f.follow_id;", new BeanPropertyRowMapper<>(userFollow.class), userId);
            result.setCode(200);
            result.setResult(followuserlist);
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }
    }

    @ApiOperation(value = "添加关注",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示关注成功，201表示关注异常，2011表示取消关注成功")
    @GetMapping("/addFollow")
    public Result addFollow(@ApiParam(name = "userId", value = "用户ID", required = true)Integer userId,
                            @ApiParam(name = "followId", value = "我的关注用户ID", required = true)Integer followId){
        Result result = new Result();
        try {
            Integer followOrNot = jdbc.queryForObject("select count(*) from follow where user_id=? and follow_id =?;", Integer.class, userId, followId);
            if(followOrNot == 1){
                try {
                    jdbc.update("delete from follow where user_id = ? and follow_id = ?",userId,followId);
                    result.setCode(2011);
                    result.setResult("取消关注成功");
                } catch (DataAccessException e) {
                    e.printStackTrace();
                    result.setCode(201);
                    result.setResult("异常!"+e.getMessage());
                }

            }else{
                jdbc.update("insert into follow(user_id, follow_id) VALUE (?,?);",userId,followId);
                result.setCode(200);
                result.setResult("关注成功!");
            }
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }
    }

    @ApiOperation(value = "判断是否关注",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:2011表示已关注，200表示未关注，201表示关注异常")
    @GetMapping("/addFollowLogic")
    public Result addFollowLogic(@ApiParam(name = "userId", value = "用户ID", required = true)Integer userId,
                                 @ApiParam(name = "followId", value = "我的关注用户ID", required = true)Integer followId){
        Result result = new Result();
        try {
            Integer followOrNot = jdbc.queryForObject("select count(*) from follow where user_id=? and follow_id =?;", Integer.class, userId, followId);
            if(followOrNot == 1){
                result.setCode(2011);
                result.setResult("已关注");

            }else{
                result.setCode(200);
                result.setResult("未关注!");
            }
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }
    }

    //关注者的id
    @ApiOperation(value = "我的关注列表",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "获取我的关注用户的id，code:200表示成功，201表示异常")
    @GetMapping("/followId")
    public Result followId(@ApiParam(name = "userId", value = "用户ID", required = true)Integer userId){
        Result result = new Result();
        try {
            List<Map<String, Object>> followIdList = jdbc.queryForList("select follow_id from follow where user_id = ?;", userId);
            result.setCode(200);
            result.setResult(followIdList);
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }

    }

    @ApiOperation(value = "点击关注",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示关注成功，201表示关注异常")
    @GetMapping("/followOnly")
    public Result followOnly(@ApiParam(name = "userId", value = "用户ID", required = true)Integer userId,
                             @ApiParam(name = "followId", value = "我的关注用户ID", required = true)Integer followId){
        Result result = new Result();
        try {
            jdbc.update("insert into follow(user_id, follow_id) VALUE (?,?);",userId,followId);
            result.setCode(200);
            result.setResult("关注成功！");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }

    }

    @ApiOperation(value = "取消关注",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示取消关注成功，201表示取消关注异常")
    @GetMapping("/notFollowOnly")
    public Result notFollowOnly(@ApiParam(name = "userId", value = "用户ID", required = true)Integer userId,
                                @ApiParam(name = "followId", value = "我的关注用户ID", required = true)Integer followId){
        Result result = new Result();
        try {
            jdbc.update("delete from follow where User_id=? and follow_id=?;",userId,followId);
            result.setCode(200);
            result.setResult("取消关注成功！");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }

    }

    @ApiOperation(value = "我的关注数量统计",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @GetMapping("/userFollowsNum")
    public Result userFollowsNum(){
        Result result = new Result();
        try {
            List<Map<String, Object>> follownum = jdbc.queryForList("select count(*) as followsnum from follow group by follow_id order by followsnum desc;");
            result.setCode(200);
            result.setResult(follownum);
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }
    }

    @ApiOperation(value = "修改头像",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @GetMapping("/changeUserImg")
    public Result changeUserImg(@ApiParam(name = "userImg", value = "用户头像", required = true)String userImg,
                                @ApiParam(name = "userId", value = "用户ID", required = true)Integer userId){
        Result result = new Result();
        try {
            jdbc.update("update user set user_img = ? where User_id = ?;",userImg,userId);
            result.setCode(200);
            result.setResult("修改头像成功");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("异常"+e.getMessage());
            return result;
        }
    }

    @ApiOperation(value = "验证码核验",
            protocols = "http",
            httpMethod = "GET",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @GetMapping("/checkExam")
    public Result checkExam(@ApiParam(name = "phone", value = "电话号码", required = true)String phone,
                            @ApiParam(name = "exam", value = "验证码", required = true)String exam){
        Result result = new Result();
        try {
            Integer rightOrNot = jdbc.queryForObject("select count(*) from user where phone = ? and exam = ?;", Integer.class, phone, exam);
            result.setCode(200);
            result.setResult(rightOrNot);
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("查询失败"+e.getMessage());
            return result;
        }
    }

    @ApiOperation(value = "设置新密码",
            protocols = "http",
            httpMethod = "POST",
            consumes = "application/json",
            response = Result.class,
            notes = "code:200表示成功，201表示异常")
    @PostMapping("/setNewPassword")
    public Result setNewPassword(@RequestBody User user){
        Result result = new Result();
        try {
            jdbc.update("update user set password = ? where account = ?;",user.getPassword(),user.getAccount());
            result.setCode(200);
            result.setResult("设置新密码成功");
            return result;
        } catch (DataAccessException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setResult("设置新密码失败"+e.getMessage());
            return result;
        }
    }



}


